<template>
  <el-dialog top="80px"
    :visible.sync="isVisible"
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-container>
      <el-main v-loading="submitLoading"
        :style="{ 'max-height': maxHeightDialog }"
        :element-loading-text="submitLoading ? '提交中...' : '加载中...'"
        class="container-main">
        <el-form ref="elForm"
          size="small"
          label-position="right"
          :model="form"
          :rules="rules"
          label-width="160px">
          <div>
            <div class="title">
              <span>填写基本信息</span>
            </div>
            <el-card class="card"
              shadow="never"
              style="background: #fafafa">
              <div>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="所属部门">
                      <treeselect v-model="form.deptGuid"
                        placeholder="选择所属部门"
                        :options="deptTreeDataList"
                        :default-expand-level="Infinity"
                        style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所属网格">
                      <treeselect v-model="form.gridMount"
                        placeholder="选择所属网格"
                        :options="gridTreeDataList"
                        :default-expand-level="Infinity"
                        style="width: 100%"
                        @select="onGridSelect">
                        <div slot="value-label"
                          slot-scope="{ node }">
                          {{ node.raw.fullPathText }}
                        </div>
                      </treeselect>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="设备类型"
                      prop="deviceType">
                      <el-select v-model="form.deviceType"
                        popper-class="global-select"
                        placeholder="选择设备类型"
                        clearable
                        filterable
                        @change="deviceTypeChange">
                        <el-option v-for="item in deviceDictionaries"
                          :key="item.dictValue"
                          :label="item.dictText"
                          :value="item.dictValue" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="设备区分"
                      prop="deviceIsLine">
                      <el-select v-model="form.deviceIsLine"
                        popper-class="global-select"
                        placeholder="选择设备区分"
                        clearable
                        filterable
                        :disabled="true">
                        <el-option v-for="item in searchArray.deviceIsLineList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="消防主机编码">
                      <el-select v-model="form.hostId"
                        placeholder="请选择消防主机编码"
                        style="width: 100%"
                        @change="hostCount"
                        clearable
                        :disabled="true">
                        <el-option v-for="item in fireMainList"
                          :key="item.hostCode"
                          :label="item.hostCode"
                          :value="item.hostCode">
                          <span style="float: left">{{ item.hostCode }}</span>
                          <span
                            style="float: right; color: #8492a6; font-size: 13px">{{ item.hostName }}</span>
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="消防主机名称">
                      <el-input v-model="hostName"
                        :disabled="true"></el-input></el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="通讯类型"
                      prop="communicationType">
                      <el-select v-model="form.communicationType"
                        popper-class="global-select"
                        placeholder="选择通讯类型"
                        clearable
                        filterable
                        @change="communicationTypeChange">
                        <el-option v-for="item in communicationData"
                          :key="item.dictValue"
                          :label="item.dictText"
                          :value="item.dictValue" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="关联网关"
                      prop="gatewayId">
                      <el-select v-model="form.gatewayId"
                        popper-class="global-select"
                        placeholder="选择关联网关"
                        clearable
                        filterable
                        :disabled="!isSelectedGateway"
                        @change="gatewayChange">
                        <el-option v-for="item in gatewayList"
                          :key="item.id"
                          :label="item.gatewayName"
                          :value="item.id" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="设备编码"
                      prop="deviceCode">
                      <el-input v-model="form.deviceCode"
                        placeholder="输入设备编码"
                        clearable
                        @input="onDeviceCodeInput" />
                    </el-form-item>


                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="设备内部编码">
                      <el-input v-model="form.deviceSource"
                        :disabled="true"></el-input></el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="设备名称"
                      prop="deviceName">
                      <el-input v-model="form.deviceName"
                        placeholder="输入设备名称"
                        clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="设备型号"
                      prop="deviceModel">
                      <!-- <el-input
                        v-model="form.deviceModel"
                        placeholder="输入设备型号"
                        clearable
                      /> -->
                      <el-select v-model="form.deviceModel"
                        popper-class="global-select"
                        placeholder="选择设备型号"
                        clearable
                        filterable>
                        <el-option v-for="item in deviceModelList"
                          :key="item.dictValue"
                          :label="item.dictText"
                          :value="item.dictText" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="设备使用情况"
                      prop="status">
                      <el-select v-model="form.status"
                        popper-class="global-select"
                        placeholder="选择设备使用情况"
                        clearable
                        filterable>
                        <el-option v-for="item in searchArray.statusList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="设备运行状态"
                      prop="deviceRunningState">
                      <el-select v-model="form.deviceRunningState"
                        popper-class="global-select"
                        placeholder="设备运行状态"
                        clearable
                        filterable
                        :disabled="true">
                        <el-option
                          v-for="item in searchArray.deviceRunningStateList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="设备是否激活">
                      <el-select v-model="form.isActive"
                        popper-class="global-select"
                        placeholder="选择设备是否激活"
                        clearable
                        filterable>
                        <el-option v-for="item in searchArray._activeList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="激活时间">
                      <el-date-picker v-model="form.activationTime"
                        type="datetime"
                        align="right"
                        :picker-options="globalConstant.PICKER_OPTIONS"
                        placeholder="选择激活时间" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="设备使用周期(单位:年)"
                      prop="lifeCycle">
                      <el-input v-model="form.lifeCycle"
                        placeholder="输入设备使用周期"
                        clearable />
                    </el-form-item>
                    <span
                      style="margin-left: 160px;font-size: 12px;color: #f56c6c;position: relative;top: -3px;">
                      提示：只能输入大于0的正整数
                    </span>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="告警方式"
                      prop="alertMethod">
                      <el-select v-model="form.alertMethod"
                        popper-class="global-select"
                        placeholder="选择告警方式"
                        clearable>
                        <el-option v-for="item in alertMethodList"
                          :key="item.dictValue"
                          :label="item.dictText"
                          :value="item.dictValue" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="设备所在位置"
                      prop="deviceLocation">
                      <el-input v-model="form.deviceLocation"
                        placeholder="输入设备位置"
                        clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="ip地址"
                      prop="ipAddr">
                      <el-input v-model="form.ipAddr"
                        placeholder="请输入ip地址"
                        clearable></el-input></el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="经度">
                      <el-input v-model="form.longitude"
                        placeholder="输入经度"
                        clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="纬度">
                      <el-input v-model="form.latitude"
                        placeholder="输入纬度"
                        clearable />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="厂家"
                      prop="manufactor">
                      <el-input v-model="form.manufactor"
                        placeholder="输入厂家"
                        clearable />
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="生产日期">
                      <el-date-picker v-model="form.manufacturingDate"
                        type="date"
                        placeholder="选择生产日期" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="设备配置">
                      <el-input v-model="form.deviceParameter"
                        placeholder="输入设备配置"
                        clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所属区域编码">
                      <el-input v-model="form.zoonId"
                        placeholder="输入所属区域编码"
                        clearable />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="所属运营商">
                      <el-select v-model="form.operator"
                        popper-class="global-select"
                        placeholder="选择所属运营商"
                        clearable
                        filterable>
                        <el-option v-for="item in searchArray.operatorList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="sim卡号">
                      <el-input v-model="form.simNo"
                        placeholder="输入sim卡号"
                        clearable />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="说明">
                      <el-input v-model="form.description"
                        type="textarea"
                        :autosize="{ minRows: 2 }"
                        placeholder="输入说明"
                        clearable />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-card>
          </div>

          <div>
            <div class="title">
              <span>配置设备属性</span>
            </div>
            <el-card class="card"
              shadow="never">
              <div class="attribute-list">
                <device-attribute-list :source-list="attributeList"
                  :operation-type="operationType"
                  @resetOperationType="operationType = ''">
                  <template slot="add">
                    <el-col :span="8">
                      <el-form-item style="float: right">
                        <el-button class="btn-add"
                          size="mini"
                          round
                          @click="toAddAttribute({}, -1, 'add')">
                          <i class="iconfont icon-xinzenghuizong"
                            style="font-size: 13px" />
                          添加
                        </el-button>
                      </el-form-item>
                    </el-col>
                  </template>
                  <template slot="operation">
                    <el-table-column align="center"
                      label="操作区"
                      width="120">
                      <template slot-scope="{ row, $index }">
                        <i class="iconfont icon-bianji2 i-edit"
                          @click="toAddAttribute(row, $index, 'edit')" />
                        <i class="iconfont icon-fengefu fengefu" />
                        <el-popconfirm :title="'确定删除【' + row.name + '】该属性吗？'"
                          placement="top"
                          @confirm="toSingleDelete(row, $index, '确定')"
                          @cancel="toSingleDelete(row, $index, '取消')">
                          <i slot="reference"
                            class="iconfont icon-shanchu i-delete" />
                        </el-popconfirm>
                      </template>
                    </el-table-column>
                  </template>
                </device-attribute-list>
              </div>
            </el-card>
          </div>
        </el-form>
      </el-main>

      <el-footer>
        <el-button size="medium"
          icon="el-icon-close"
          :disabled="submitLoading"
          style="width: 120px; margin-right: 10px"
          @click="isVisible = false">
          取消
        </el-button>
        <el-button size="medium"
          type="primary"
          icon="el-icon-check"
          :disabled="submitLoading"
          :loading="submitLoading"
          style="width: 120px"
          @click="toSubmit">
          {{ params.item.id == -1 ? "提交" : "修改" }}
        </el-button>
      </el-footer>
    </el-container>
    <device-attribute-add v-if="attributeDialogObj.isVisible"
      :dialog-visible="attributeDialogObj.isVisible"
      :title="attributeDialogObj.title"
      :params-attribute="paramsAttribute"
      @close="dialogClose('attributeDialogObj')"
      @save="toSaveAttribute" />
  </el-dialog>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import globalConstant from "@/utils/constants";
import DeviceAttributeAdd from "./AddAttribute";
import DeviceAttributeList from "./AttributeList";
// import DeviceMap from './Map'
import dataFormMixins from "@/mixins/data-form-mixins";
import deviceManageApi from "@/api/device-manage";
import recDataDeviceList from "../device-list.js";

import { validIPAddr } from "@/utils/my-validate";
import { validNumber } from "@/utils/my-validate";
import fireFightManageApi from "@/api/firefight-manage";

export default {
  name: "DeviceAdd",
  components: {
    Treeselect,
    DeviceAttributeAdd,
    DeviceAttributeList
    // DeviceMap
  },
  mixins: [dataFormMixins],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    params: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data () {
    return {
      searchArray: { ...recDataDeviceList.RecDataSearchArray },
      deptTreeDataList: [],
      deptTreeLoading: false,
      gridTreeDataList: [],
      attributeDialogObj: {
        isVisible: false,
        title: ""
      },
      paramsAttribute: {},
      editIndex: -1,
      attributeList: [],
      monitorLogList: [],
      operationType: "",
      inputLocationDialogObj: {
        isVisible: false,
        title: ""
      },
      deviceDictionaries: [],

      deviceSourceVerification: false,

      fireMainList: [], //消防主机列表
      hostName: "",
      communicationData: [],
      gatewayList: [],

      deviceModelList: [],
      alertMethodList: [
        { dictValue: 1, dictText: "允许重复告警" },
        { dictValue: 2, dictText: "不允许重复告警" }
      ],


      equipmentCodeRuleInfo: {},
      isSelectedGateway: false
    };
  },
  computed: {
    isVisible: {
      get () {
        return this.dialogVisible;
      },
      set () {
        this.toClose();
      }
    },
    user () {
      return this.$store.state.account.user;
    },
    globalConstant () {
      return { ...globalConstant };
    }
  },

  created () { },
  mounted () {
    this.rules = this.initRules();
    this.form = this.initForm();

    this.getSelectData()

    if (this.params.item.id !== -1) {
      this.getDetail();
    }

  },
  methods: {
    initForm () {
      return {
        id: -1,
        deptGuid: null, // 部门id
        gridMount: null, // 实际挂载点的guid
        gridMountFullPath: "", // 挂载网点的全路径
        gridMountFullPathText: "", // 挂载网点的全路径文本
        gridRegion: "", // 网格表中层级1的网点guid
        gridUnit: "", // 网格表中层级2的网点guid
        // gridMountList:[],

        deviceIsLine: 1, // 设备区分
        hostId: null, // 消防主机id
        deviceCode: "", // 设备内部编码
        deviceSource: "", // 设备编码(原厂家编号)
        deviceName: "", // 设备名称
        deviceType: "", // 设备类型
        deviceModel: "", // 设备型号
        status: "", // 设备使用情况
        deviceRunningState: "正常", // 设备运行状态
        deviceLocation: "", // 设备所在位置
        latitude: "", // 纬度
        longitude: "", // 经度
        ipAddr: "", // ip地址

        manufactor: "", // 厂家
        manufacturingDate: "", // 生产日期
        deviceParameter: "", // 设备配置
        zoonId: "", // 所属区域编码

        communicationType: "", //  通讯类型
        gatewayId: "", //  网关设备ID
        gatewayName: "", //  网关设备名称

        operator: "", // 所属运营商
        simNo: "", // sim卡号
        isActive: "", // 设备是否激活
        activationTime: "", // 激活时间
        lifeCycle: null, // 设备使用周期
        description: "", // 说明
        alertMethod: 1, //告警方式

      };
    },
    initRules () {
      return {
        deptGuid: this.getValidatorForm("change"),
        gridMount: this.getValidatorForm("change"),
        deviceIsLine: this.getValidatorForm("change"),
        deviceCode: this.getValidatorForm(),
        deviceName: this.getValidatorForm(),
        deviceType: this.getValidatorForm("change"),
        alertMethod: this.getValidatorForm("change"),
        deviceModel: this.getValidatorForm(),
        status: this.getValidatorForm("change"),
        deviceRunningState: this.getValidatorForm("change"),
        deviceLocation: this.getValidatorForm(),
        communicationType: this.getValidatorForm(),
        ipAddr: [
          {
            validator: (rule, value, callback) => {
              if (value && value != '') {
                const reg = /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/
                if (!reg.test(value)) {
                  callback(new Error('ip地址输入的值不正确'));
                }
              }
              callback()
            }, trigger: 'blur'
          }
        ],
        lifeCycle: [
          {
            validator: (rule, value, callback) => {
              if (value && value != '') {
                const reg = /^\+?[1-9][0-9]*$/
                if (!reg.test(value)) {
                  callback(new Error('设备使用周期输入的值不正确'));
                }
              }
              callback()
            }, trigger: 'blur'
          }
        ],
      };
    },


    getSelectData () {
      // 部门树
      deviceManageApi
        .getDeptTree()
        .then(ret => {
          this.deptTreeDataList = ret.data.data.rows;
          this.deptTreeDataList.forEach(ele => {
            this.getDeptGuidTree(ele);
          });
        })
        .catch(() => {
          this.deptTreeDataList = [];
        });

      // 网格树
      deviceManageApi
        .getGridTree()
        .then(ret => {
          this.gridTreeDataList = ret.data.data.rows;
        })
        .catch(() => {
          this.gridTreeDataList = [];
        });

      // 设备类型
      deviceManageApi.getDictValueAttr({
        fieldName: "collect_type",
        tableName: "t_equipment_collect"
      }).then(ret => {
        this.deviceDictionaries = ret.data.dictValue;
      });

      // 消防主机
      fireFightManageApi.getFireMainList().then(res => {
        if (res.status === 200) {
          this.fireMainList = res.data.data.rows;
        }
      });

      // 通讯类型
      deviceManageApi.getDictValueAttr({
        fieldName: "communication_type",
        tableName: "t_communication"
      }).then(r => {
        this.communicationData = r.data.dictValue;
      });

      // 关联网关
      deviceManageApi.getGateway({ pageNum: 1, pageSize: 99999 }).then(e => {
        if (e.data.code == 200) {
          this.gatewayList = e.data.data.rows;
        }
      });

      //设备型号
      deviceManageApi.getDictValueAttr({
        fieldName: "collect_model",
        tableName: "t_equipment_collect"
      }).then(r => {
        this.deviceModelList = r.data.dictValue;
      });

    },
    getDeptGuidTree (ele) {
      ele.id = ele.guid;
      if (ele.children) {
        ele.children.forEach(chilEle => {
          this.getDeptGuidTree(chilEle);
        });
      }
    },

    getDetail () {
      this.loading = true;
      deviceManageApi
        .getDeviceDetail({ id: this.params.item.id })
        .then(ret => {
          this.detailObj = ret.data.data;
          this.attributeList = this.detailObj.equipmentAttributes;
          this.monitorLogList = this.detailObj.equipmentMonitorLogList;

          this.form = { ...this.detailObj };

          this.form.deviceType = Number(this.form.deviceType);
          this.form.lifeCycle = this.detailObj.lifeCycle
            ? this.detailObj.lifeCycle
            : "";
          if (
            this.form.manufacturingDate &&
            this.form.manufacturingDate != ""
          ) {
            this.form.manufacturingDate = new Date(
              new Date(this.form.manufacturingDate)
            );
          }
          if (this.form.hostId) {
            this.hostName = this.fireMainValue(this.form.hostId)
              ? this.fireMainValue(this.form.hostId)
              : "";
          }

          this.getEquipmentCodeRuleInfo()

          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    fireMainValue (hostId) {
      let obj = this.fireMainList.find(val => {
        return hostId.toString() == val.hostCode;
      });
      if (obj) {
        // return obj.hostCode
        return obj.hostName;
      }
    },

    onGridSelect (node, instanceId) {
      this.form.gridMountFullPath = node.fullPath;
      this.form.gridMountFullPathText = node.fullPathText
        ? node.fullPathText
        : "";
      this.form.longitude = node.longitude;
      this.form.latitude = node.latitude;
    },
    // 关联设备编码拼接
    hostCount (val) {
      // this.ruleForm.deviceSource = val + this.ruleForm.deviceCode
      this.hostName = this.fireMainValue(val) ? this.fireMainValue(val) : "";
    },

    deviceTypeChange () {
      this.getEquipmentCodeRuleInfo()
      this.form.gatewayId = null;
    },
    communicationTypeChange () {
      this.getEquipmentCodeRuleInfo()
      this.form.gatewayId = null;
    },
    gatewayChange () {
      this.getDeviceSource()
    },
    // 获取编码规则
    getEquipmentCodeRuleInfo () {
      if (this.form.communicationType && this.form.deviceType) {
        deviceManageApi.getEquipmentCodeRuleInfo({
          communicationType: this.form.communicationType,
          deviceType: this.form.deviceType
        }).then((res) => {
          this.equipmentCodeRuleInfo = res.data.data
          if (this.equipmentCodeRuleInfo && this.equipmentCodeRuleInfo.isLinkGateway) {
            this.isSelectedGateway = true
          } else {
            this.isSelectedGateway = false
            this.form.gatewayId = null;
          }
          this.getDeviceSource()
        })
      } else {
        this.equipmentCodeRuleInfo = {}
        this.isSelectedGateway = false
        this.form.gatewayId = null;
        this.getDeviceSource()
      }
    },

    onDeviceCodeBlur () {
      this.getDeviceSource()
    },
    onDeviceCodeInput (val) {
      this.getDeviceSource()
    },
    getDeviceSource () {
      let prefixCode = ''
      if (this.equipmentCodeRuleInfo) {
        if (this.equipmentCodeRuleInfo.isLinkGateway) {
          const item = this.gatewayList.find((val) => {
            return val.id == this.form.gatewayId
          })
          prefixCode = item ? item.snNumber : ''
        } else {
          prefixCode = this.equipmentCodeRuleInfo.prefixCode
        }
      }
      if (this.form.deviceCode) this.form.deviceSource = prefixCode + this.form.deviceCode;

    },


    toAddAttribute (data, index, type) {
      this.editIndex = index;
      this.paramsAttribute = {
        operationType: type,
        item: data,
        deviceCode: this.form.deviceCode
      };
      this.attributeDialogObj.title =
        type === "add" ? "添加设备属性" : "编辑设备属性";
      this.attributeDialogObj.isVisible = true;
    },
    toSaveAttribute (data) {
      this.operationType = data.type;
      if (data.type === "add") {
        this.attributeList.unshift(data.data);
      } else {
        this.attributeList[this.editIndex] = { ...data.data };
      }
      console.log("attributeList", this.attributeList);
    },
    toSingleDelete (data, index, type) {
      if (type === "确定") {
        this.operationType = "delete";
        this.attributeList.splice(index, 1);
        this.$message.success("删除成功！");
      }
    },

    toClose () {
      this.$emit("close");
    },
    toSubmit () {
      this.$refs.elForm.validate(valid => {
        let gridParentIdList = [];
        this.gridTreeDataList.forEach(ele => {
          this.getGridParentId(ele, this.form.gridMount, gridParentIdList);
        });
        gridParentIdList.unshift(this.form.gridMount);
        gridParentIdList = gridParentIdList.reverse();
        this.form.gridRegion = gridParentIdList[0];
        if (gridParentIdList.length >= 2) {
          this.form.gridUnit = gridParentIdList[1];
        }

        if (!this.form.gridMount) {
          this.form.gridMountFullPath = "";
          this.form.gridMountFullPathText = "";
          this.form.gridUnit = "";
          this.form.gridRegion = "";
        }

        if (valid) {
          // this.submitLoading = true

          const model = {};
          Object.keys(this.form).forEach((key) => {
            model[key] = this.form[key]
          })
          model.manufacturingDate = this.getFormatDate(
            model.manufacturingDate,
            "YYYY-MM-DD HH:mm:ss"
          );
          model.activationTime = this.getFormatDate(
            model.activationTime,
            "YYYY-MM-DD HH:mm:ss"
          );
          const list = [];
          this.attributeList.forEach(ele => {
            list.push(ele);
          });
          model.equipmentAttributes = list;
          model.equipmentMonitorLogList = this.monitorLogList;

          console.log("提交", model);
          if (this.params.item.id === -1) {
            deviceManageApi
              .addDevice(model)
              .then(ret => {
                this.submitLoading = false;
                this.isVisible = false;
                this.$message({
                  message: "提交成功！",
                  type: "success"
                });
                this.$emit("submit", "add");
              })
              .catch(() => {
                this.submitLoading = false;
              });
          } else {
            model.gridMountList = [];
            model.idList = [];
            model.curveList = [];
            deviceManageApi
              .updateDevice(model)
              .then(ret => {
                console.log(ret);
                this.submitLoading = false;
                this.isVisible = false;
                this.$message({
                  message: "修改成功！",
                  type: "success"
                });
                this.$emit("submit", "edit");
              })
              .catch(() => {
                this.submitLoading = false;
              });
          }
        } else {
          this.$message({
            message: "请完善表单内容！",
            type: "warning",
            duration: 4000
          });
          return false;
        }
      });
    },
    getGridParentId (ele, gridId, gridParentIdList) {
      if (ele.id === gridId) {
        if (ele.parentId) {
          gridParentIdList.push(ele.parentId);
          this.gridTreeDataList.forEach(item => {
            this.getGridParentId(item, ele.parentId, gridParentIdList);
          });
        }
      } else {
        if (ele.children) {
          ele.children.forEach(childEle => {
            this.getGridParentId(childEle, gridId, gridParentIdList);
          });
        }
      }
    },




  }
};
</script>

<style lang="scss" scoped>
@import "../../../../../styles/part-custom";

.btn-add-attribute {
  margin-top: -12px;
  padding-bottom: 3px;
}

.btn-add {
  background: transparent;
  padding: 6px 15px !important;
  color: #f7a20d;
  border: 1px solid #f7a20d;
  transition: all 0.5s;
  margin-left: 20px;
}

.btn-add:hover {
  color: #f9c66c;
  border: 1px solid #f9c66c;
}

.fengefu {
  font-size: 14px;
  color: #409eff;
  font-weight: 550;
  margin: 0px 6px;
}

.text-save {
  color: #ff6363;
  font-size: 14px;
  cursor: pointer;
  margin-left: -3px;
}

.text-cancle {
  color: #f9c65b;
  font-size: 14px;
  cursor: pointer;
  margin-right: -3px;
}

.i-edit {
  color: #f9c65b;
  font-size: 19px;
  cursor: pointer;
}

.i-delete {
  color: #ff6363;
  font-size: 17px;
  cursor: pointer;
}

.attribute-list>>>.el-table td:last-child {
  border-left: 0px solid #ebeef5;
}
</style>
